package com.magnificent.atlantis.client.scheduler.logger;

import com.magnificent.atlantis.client.data.user.UserContext;
import com.magnificent.commons.utils.collections.list.MetaArrayList;
import com.magnificent.commons.utils.collections.list.MetaList;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * User: Babanin
 * Date: 09.08.2009
 * Time: 6:28:33
 */
public class UserThreadLogger {
    private static Map<UserContext, UserThreadLogger> instances = new HashMap<UserContext, UserThreadLogger>();

    private int id;
    private MetaList<LoggerEvent> events;
    private MetaList<LoggerEventListener> listeners;

    public UserThreadLogger() {
        id = 0;
        events = new MetaArrayList<LoggerEvent>();
        listeners = new MetaArrayList<LoggerEventListener>();
    }

    public synchronized void info(String message) {
        log(new Date(), "[INFO]    " + message, LoggerEvent.EventType.INFO);
    }

    public synchronized void warning(String message) {
        log(new Date(), "[WARNING] " + message, LoggerEvent.EventType.WARNING);
    }

    public synchronized void error(String message) {
        log(new Date(), "[ERROR]   " + message, LoggerEvent.EventType.ERROR);
    }

    public synchronized void log(Date date, String message, LoggerEvent.EventType eventType) {
        final LoggerEvent event = new LoggerEvent(id++, date, message, eventType);

        events.add(event);
        for (LoggerEventListener listener : listeners) {
            listener.newLogEvent(event);
        }
    }

    public MetaList<LoggerEvent> getEvents() {
        return events;
    }

    public static UserThreadLogger getInstance(UserContext context) {
        UserThreadLogger userThreadLogger = instances.get(context);

        if (userThreadLogger == null) {
            userThreadLogger = new UserThreadLogger();
            instances.put(context, userThreadLogger);
        }

        return userThreadLogger;
    }

    public void addLoggerListener(LoggerEventListener listener) {
        listeners.add(listener);
    }

    public static interface LoggerEventListener {
        public void newLogEvent(LoggerEvent event);
    }
}
